import React, { useEffect, useState } from 'react';
import { Card, Input, Select, Button, message, Form } from 'antd';
import { Editor } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';
import 'bytemd/dist/index.css';
import { useNavigate, useLocation, useParams } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { addPost, updatePost, getPostById } from '@/api/communityPostController';
import { listCategories } from '@/api/communityCategoryController';
import { listCommunityTags } from '@/api/communityTagController';
import Header from '@/components/Header/Header';
import zhHans from 'bytemd/locales/zh_Hans.json';

const plugins = [
  gfm(),
  highlight(),
];

interface Category {
  categorycode: string;
  categorynamezh: string;
}

interface Tag {
  tagcode: number;
  tagnamezh: string;
}

const CreatePost: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [tags, setTags] = useState<Tag[]>([]);
  const [content, setContent] = useState('');

  // 从 location.state 中获取帖子数据
  const { isEdit, post } = location.state || {};

  // 加载分类和标签数据
  useEffect(() => {
    const fetchCategoriesAndTags = async () => {
      try {
        // 获取分类列表
        const categoryResponse = await listCategories();
        if (categoryResponse.code === 200) {
          setCategories(categoryResponse.data);
        }

        // 获取标签列表
        const tagResponse = await listCommunityTags();
        if (tagResponse.code === 200) {
          setTags(tagResponse.data);
        }
      } catch (error) {
        console.error('Failed to fetch categories or tags:', error);
        message.error('加载分类或标签失败');
      }
    };

    fetchCategoriesAndTags();
  }, []);

  // 设置表单初始值
  useEffect(() => {
    if (isEdit && post) {
      form.setFieldsValue({
        title: post.title,
        categorycode: post.categorycode,
        tagcode: post.tagcode
      });
      setContent(post.content);
    }
  }, [isEdit, post, form]);

  const onFinish = async (values: any) => {
    if (!content.trim()) {
      message.error('请输入帖子内容');
      return;
    }

    setLoading(true);
    try {
      const postData = {
        ...values,
        content: content,
        id: isEdit ? post.id : undefined
      };

      const api = isEdit ? updatePost : addPost;
      const response = await api(postData);
      
      if (response.code === 200) {
        message.success(isEdit ? '更新成功' : '发布成功');
        navigate(-1);
      } else {
        message.error(response.message || (isEdit ? '更新失败' : '发布失败'));
      }
    } catch (error) {
      console.error('Failed to submit post:', error);
      message.error(isEdit ? '更新失败' : '发布失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      
      {/* 移动端顶部导航 */}
      <div className="lg:hidden">
        <Card className="shadow-sm rounded-none" bodyStyle={{ padding: '12px 24px' }}>
          <div className="flex items-center">
            <ArrowLeftOutlined 
              className="text-lg cursor-pointer" 
              onClick={() => navigate(-1)}
            />
            <span className="flex-1 text-center text-lg font-medium">发布帖子</span>
          </div>
        </Card>
      </div>

      <div className="max-w-[1400px] mx-auto py-8 px-4">
        <Card className="shadow-sm">
          <Form
            form={form}
            layout="vertical"
            requiredMark="optional"
            onFinish={onFinish}
          >
            <Form.Item
              name="title"
              label={<span className="font-bold text-base">标题 *</span>}
              rules={[
                { required: true, message: '请输入标题' },
                { max: 100, message: '标题最多100个字符' },
                { min: 2, message: '标题至少2个字符' }
              ]}
            >
              <Input 
                placeholder="请输入帖子标题" 
                maxLength={100}
                showCount
              />
            </Form.Item>

            <Form.Item 
              label={<span className="font-bold text-base">内容 *</span>}
              required
              rules={[{ required: true, message: '请输入内容' }]}
              validateTrigger="onBlur"
            >
              <div className={!post?.content.trim() ? 'border-red-500' : ''}>
                <Editor
                  value={content}
                  plugins={plugins}
                  onChange={(v) => setContent(v)}
                  placeholder="请输入帖子内容..."
                  locale={zhHans}
                />
              </div>
              {!post?.content.trim() && (
                <div className="text-red-500 mt-1 text-sm">请输入内容</div>
              )}
            </Form.Item>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Form.Item
                name="categorycode"
                label={<span className="font-bold text-base">分类 *</span>}
                rules={[
                  { required: true, message: '请选择分类' },
                  { type: 'string', message: '请选择有效的分类' }
                ]}
              >
                <Select 
                  placeholder="请选择帖子分类"
                  className="w-full"
                >
                  {categories.map(category => (
                    <Select.Option 
                      key={category.categorycode} 
                      value={category.categorycode}
                    >
                      {category.categorynamezh}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                name="tagcode"
                label={<span className="font-bold text-base">标签 *</span>}
                rules={[
                  { required: true, message: '请选择标签' },
                  { type: 'number', message: '请选择有效的标签' }
                ]}
              >
                <Select 
                  placeholder="请选择帖子标签"
                  className="w-full"
                >
                  {tags.map(tag => (
                    <Select.Option 
                      key={tag.tagcode} 
                      value={tag.tagcode}
                    >
                      {tag.tagnamezh}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </div>

            <div className="flex justify-end gap-4 mt-6">
              <Button 
                onClick={handleReset}
                size="large"
              >
                重置
              </Button>
              <Button 
                type="primary" 
                htmlType="submit"
                loading={loading}
                size="large"
              >
                {isEdit ? '更新' : '发布帖子'}
              </Button>
            </div>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default CreatePost; 